package com.example.kliven.because.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;


import android.os.Handler;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.kliven.because.R;
import com.example.kliven.because.Singleton.VolleySingleton;
import com.example.kliven.because.activity.HealthDetailActivity;
import com.example.kliven.because.adapter.HealthAdapter;
import com.example.kliven.because.bean.AdEntity;
import com.example.kliven.because.bean.HealthBean;
import com.example.kliven.because.intentbean.NetFashionBean;
import com.example.kliven.because.intentbean.NetHealthBean;
import com.google.gson.Gson;
import android.os.Message;
import android.widget.TextView;
import android.widget.Toast;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Kliven on 16/1/11.
 */
public class HealthFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    private String url = "http://zzd.sm.cn/appservice/api/v1/channel/472933935?client_os=android&client_version=2.1.0.1&bid=800&m_ch=005&city=0411&sn=eda7198b96b6b6239a7f5b39114635e0&content_cnt=20&recoid=14211241269251732116&ftime=1452850500421&method=new&count=20";
    public static List<HealthBean> healthBeans;
    private ListView listView;
    private List<AdEntity> list=new ArrayList<AdEntity>();
    private SwipeRefreshLayout swipeRefreshLayout;
    private HealthAdapter healthAdapter;
    private ViewPager headViewPager;
    private TextView tv_ViewPager;
    private LinearLayout linearLayout_viewPage;

    private String title;
    private String info;
    private String id;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view  = inflater.inflate(R.layout.health_fragment, null);
        listView = (ListView) view.findViewById(R.id.list_view_health);
        View viewHead = LayoutInflater.from(getActivity()).inflate(R.layout.item_health_lv_head, null);
        listView.addHeaderView(viewHead);
        listView.setOnItemClickListener(this);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh_layout_health);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);
        swipeRefreshLayout.setOnClickListener(this);
        VolleySingleton.getInstance();
        initPagerView(view);
        initPagerListener();
        initPagerData();
        getNetData();
        return view;
    }

    private void initPagerView(View view) {
        headViewPager = (ViewPager) view.findViewById(R.id.viewPager);
        tv_ViewPager = (TextView) view.findViewById(R.id.tv_text);
        linearLayout_viewPage = (LinearLayout) view.findViewById(R.id.dot);
    }

    private Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            headViewPager.setCurrentItem(headViewPager.getCurrentItem()+1);
            handler.sendEmptyMessageDelayed(0, 3000);
        };
    };

    private void initPagerData() {
        list.add(new AdEntity(R.mipmap.health1, "人类对健康的要求"));
        list.add(new AdEntity(R.mipmap.health2, "锻炼增强体质"));
        list.add(new AdEntity(R.mipmap.health3, "家人的健康最重要"));
        list.add(new AdEntity(R.mipmap.health4, "呵护你我他"));
        list.add(new AdEntity(R.mipmap.health5, "养生之道"));
        initDots();
        headViewPager.setAdapter(new MyViewPager());
        int centerValue=Integer.MAX_VALUE/2;
        int value=centerValue%list.size();
        headViewPager.setCurrentItem(centerValue - value);
        updateTextAndDot();

        handler.sendEmptyMessageDelayed(0, 3000);
    }

    private void initDots() {
        for (int i = 0; i < list.size(); i++) {
            View view=new View(getActivity());
            LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(8,8);
            if(i!=0){
                params.leftMargin=5;
            }

            view.setLayoutParams(params);
            view.setBackgroundResource(R.mipmap.moren);
            linearLayout_viewPage.addView(view);
        }

    }

    private void initPagerListener() {
        headViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                updateTextAndDot();

            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                // TODO Auto-generated method stub

            }
        });
    }

    private void updateTextAndDot() {
        int currentPage=headViewPager.getCurrentItem()%list.size();
        tv_ViewPager.setText(list.get(currentPage).getText());

        for (int i = 0; i < linearLayout_viewPage.getChildCount(); i++) {
            linearLayout_viewPage.getChildAt(i).setEnabled(i==currentPage);
        }

    }

    private void getNetData() {
        VolleySingleton.addRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                healthBeans = new ArrayList<>();
                Gson gson = new Gson();
                NetHealthBean netHealthBean = gson.fromJson(response,NetHealthBean.class);
                for (int i = 0; i < netHealthBean.getData().getArticle().size(); i++) {
                    HealthBean healthBean = new HealthBean();
                    healthBean.setTitle(netHealthBean.getData().getArticle().get(i).getTitle());
                    healthBean.setCompany(netHealthBean.getData().getArticle().get(i).getSite());
                    healthBean.setInfo(netHealthBean.getData().getArticle().get(i).getContent());
                    for (int j = 0; j < netHealthBean.getData().getArticle().get(i).getImage().size(); j++) {
                        healthBean.setMain_img_url(netHealthBean.getData().getArticle().get(i).getImage().get(j).getUrl());
                    }
                    healthBeans.add(healthBean);
                }
                healthAdapter = new HealthAdapter(getActivity(),healthBeans);
                listView.setAdapter(healthAdapter);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent healthIntent = new Intent(getActivity(),HealthDetailActivity.class);
        Bundle setB = new Bundle();
        setB.putString("p", position + "");
        healthIntent.putExtra("bundle",setB);
        startActivity(healthIntent);
        getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
        Toast.makeText(getActivity(), "点击了第" + position, Toast.LENGTH_SHORT).show();
    }

    private class MyViewPager extends PagerAdapter {

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view==object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            AdEntity adImage = list.get(position%list.size());
            View view=View.inflate(getActivity(), R.layout.adapter,null);
            ImageView image=(ImageView) view.findViewById(R.id.image);
            image.setImageResource(adImage.getImage());

            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//			super.destroyItem(container, position, object);
            container.removeView((View) object);
        }
    }
}